import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { appConfig, codStatus } from '../../config/config';
import { Logger } from '../utils/log4js/log4js';
// import { LogService } from "../log/log.service";

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  // constructor(private readonly logService: LogService) {}
  catch(exception: any, host: ArgumentsHost) {
    const request = host.switchToHttp().getRequest();
    const response = host.switchToHttp().getResponse();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    console.log('请求拦截：', request.headers);
    // const publicRoute = ['/user/login', '/user/createUser', '/user/wx', '/user/wechatQr', '/user/qq']
    // if (!(request.originalUrl in publicRoute)) {
    //   const token = request.headers.authorization.slice(7);
    // }
    // const level = request.headers.level;
    // 自定义的异常信息结构, 响应用
    const error_info = exception.response ? exception.response : exception;
    // const error_data = exception.response?.data ? exception.response.data : {};
    const error_msg = exception.response
      ? exception.response.message
        ? exception.response.message
        : exception.response.errorMsg
      : exception.message;
    const error_code = exception.response?.errorCode
      ? exception.response.errorCode
      : exception.errorCode;
    let param;
    if (Object.keys(request.params).length) param = request.params;
    if (Object.keys(request.body).length) param = request.body;
    if (Object.keys(request.query).length) param = request.query;
    // 自定义异常结构体, 日志用
    const data = {
      ipClient: request.ip,
      routerService: request.originalUrl,
      requestMethods: request.method,
      code: status,
      message: codStatus[status],
      params: param,
      errorData: error_msg,
    };
    const logFormat = `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ${
      appConfig.serverName
    } @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 @ createDate: ${new Date().toISOString()}
 @ Method: ${request.method}
 @ IP: ${request.ip}
 @ Status code: ${status}
 @ routerService: ${JSON.stringify(request.originalUrl)}
 @ param: ${JSON.stringify(param)}
 @ errorData: ${JSON.stringify(
   error_msg,
 )} \n @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
`;
    // 404 异常响应
    if (status === 404) {
      data.message = `资源不存在! 接口 ${request.method} -> ${request.url} 无效!`;
    }
    console.log('any-exception.filter');
    Logger.error(logFormat);

    // 程序内异常捕获返回
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send({
      data: {
        msg: error_msg,
      }, // 获取全部的错误信息
      msg: data.message,
      code: status, // 自定义code
      url: request.originalUrl, // 错误的url地址
    });
  }
}
